//
//  ViewController.m
//  19-JSON网易
//
//  Created by 曹曹 on 16/8/9.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "NewsCollectionViewCell.h"
#import "NetEaseTitleLayout.h"

#define kArc4RandomColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:0.5];

@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource, NetEaseTitltLayoutDelegate>
@property (nonatomic, strong) NSMutableArray<NewsTitle *> *newsTitleArray;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong) NetEaseTitleLayout *layout;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    self.layout = (NetEaseTitleLayout *)self.myCollectionView.collectionViewLayout;
    _layout.delegate = self;
    _layout.titleFont = [UIFont systemFontOfSize:20];
}

- (void)handleData {
    NSString *newsJSONPath = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *newsJSONData = [NSData dataWithContentsOfFile:newsJSONPath];
    NSError *error = nil;
    NSDictionary *newsTitleDictionary = [NSJSONSerialization JSONObjectWithData:newsJSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDictionary[@"tList"];
    self.newsTitleArray = [NSMutableArray array];
    for (NSDictionary *dictionary in list) {
        NewsTitle *newsTitle = [NewsTitle newsTitleWithDictionary:dictionary];
        [_newsTitleArray addObject:newsTitle];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentView.backgroundColor = kArc4RandomColor;
    NewsTitle *newsTitle = _newsTitleArray[indexPath.row];
    cell.titleLabel.text = newsTitle.tname;
    cell.titleLabel.font = _layout.titleFont;
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
  widthForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *newsTitle = _newsTitleArray[indexPath.row];
    NSString *str = newsTitle.tname;
    CGRect newRect = [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.myCollectionView.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: _layout.titleFont} context:nil];
    CGFloat width = ceilf(CGRectGetWidth(newRect));
    return width;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
